﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NetTaste;
using SqlSugar;
using System.Linq.Expressions;
using System.Security.Cryptography.X509Certificates;
using VM.BLL.User;
using VM.Entity.EntityMap.Token;
using VM.Entity.EntityMap.User;

using VM.IBLL;
using VM.IBLL.Token;
using VM.IBLL.User;
using VM.IDAL;
using VM.WebCore.Jwt;

namespace VM.BLL.Token
{
    public class TokenBLL : BaseBLL, ITokenBLL
    {
        private IJWTService _IJWTService = null;
        private readonly IBLL.User.IUserBLL _userBLL;
        private readonly ISqlSuggarDAL _ISqlSuggarDAL;



        public TokenBLL(ISqlSugarClient client, IJWTService iJWTService, IBLL.User.IUserBLL userBLL, ISqlSuggarDAL sqlSuggarDAL)  
        {

            _IJWTService = iJWTService;
            _userBLL = userBLL;
            _ISqlSuggarDAL = sqlSuggarDAL;
        }

   
   
        public IActionResult generateNewAccessToken(CheckUser obj, CheckUserInfoResult checkResult)
        {
            try
            {
                //生成JWT 
                string token = _IJWTService.GetToken(obj.PublicKey);

                //生成RefreshToken

                //AddRefreshKeys()
                string refreshToken = AddRefreshToken(obj, checkResult);


                return new JsonResult(new
                {
                    status = true,
                    Msg = "鉴权成功",
                    Token = token,
                    RefreshToken = refreshToken
                });
            }
            catch (Exception e) {

                return new JsonResult(new
                {
                    status = false,
                    Msg = "鉴权失败",
                    Token = "",
                    RefreshToken = ""
                });
            }
        }

        /// <summary>
        /// 生成新的refreshToken并返回
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string AddRefreshToken(CheckUser obj, CheckUserInfoResult checkResult)
        {
            //生成RefreshToken
            Sys_RefreshToken refresh = new Sys_RefreshToken();
            refresh.GUID = Guid.NewGuid().ToString();
            refresh.RefreshKey = Guid.NewGuid().ToString();
            refresh.ClientId = obj.ClientId;
            refresh.ClientInfo = obj.ClientInfo;
            refresh.UserId = checkResult.UserId;
            refresh.Description = "创建自动生成";
            refresh.LongTimes = 7;
            refresh.StartDateTimes = DateTime.Now;
            refresh.RefreshDateTimes = DateTime.Now;
            refresh.EndDateTimes = ((DateTime)refresh.StartDateTimes).AddDays((double)refresh.LongTimes);
            refresh.PublicKey = refresh.GUID;
            _userBLL.AddRefreshKeys(refresh);
            return refresh.GUID;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="RefreshKey"></param>
        /// <returns></returns>
        public bool UpdateRefreshToken(string RefreshKey)
        {
            try
            {
                Sys_RefreshToken user = new Sys_RefreshToken();
                
                // 更新操作
             int Res=   _ISqlSuggarDAL.UpdateByNotPrimaryKey<Sys_RefreshToken>((it => it.PublicKey == "1"), (it =>  new Sys_RefreshToken()
                {

                    RefreshDateTimes = DateTime.Now,
                    EndDateTimes = DateTime.Now.AddDays(7)
                 
                   
                } ));
                if (Res > 0)
                {
                    return true; // 更新成功，返回 true
                }
                else
                {
                    return false; // 更新失败，返回 false
                }
            }
            catch (Exception ex)
            {
                // 处理异常，可以输出日志等
                Console.WriteLine("更新失败：" + ex.Message);

                return false; // 更新失败，返回 false
            }
        }

    }
}